package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2025-02-22
 * Time: 17:50
 */
public class AutotestUtils {
    public static WebDriver driver;

    public AutotestUtils(String url){
        driver = createDriver();
        driver.get(url);
    }

    /**
     * 创建驱动对象
     * @return
     */
    public static WebDriver createDriver(){
        if(driver == null){
            WebDriverManager.chromedriver().setup();
            ChromeOptions options = new ChromeOptions();
            options.addArguments("--remote-allow-origins=*");

            driver = new ChromeDriver(options);

            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(2));//默认隐式等待2秒，作用范围全局
        }
        return driver;
    }

    /**
     * 获取当前屏幕截图的时间
     */
    public List<String> getTime(){
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");//文件夹
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");//文件
        String dicName = sim1.format(System.currentTimeMillis());//文件夹格式名称，在集合中下标为0
        String fileName = sim2.format(System.currentTimeMillis());//文件格式名称，在集合中下标为1
        List<String> list = new ArrayList<>();
        list.add(dicName);
        list.add(fileName);
        return list;
    }

    /**
     * 获取屏幕截图
     */
    public void getScreenShot(String str) throws IOException {
        List<String> list = getTime();
        //dir+filename
// ./指的是当前的项⽬路径下，也就是blog_test下
// ./src/test/java/com/blogWebAutoTest/dirname/filename
// ./src/test/java/image/20230212/test01_20230212-123030毫秒.png
        String fileName = "./src/test/java/image/" + list.get(0)  + "/" + str + "-" + list.get(1) + ".png";
        File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

        FileUtils.copyFile(srcFile,new File(fileName));
    }



}
